<template>
	<view>
	<view class="poFi width-100 bgfff nav_list">
		<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="0">
			<view id="demo1" class="scroll-view-item_H fontSize-28 poRe" @click="change(item.state)" v-for="item in nav_list" :class="current==item.state?'col-C9951C':''" :key="item.id">{{item.name}} <view class="xian poAb" v-show="current==item.state"></view></view>
		</scroll-view>
	</view>
	<view class="body_view pad-lr-20 over-hid">
		<view class="pad-lr-20 pad-tb-20 radius-16 mar-top-20 bgfff" @click="goorderdetails(item.id)" v-for="item in List">
			<view class="top_state display-sb align-items fontSize-30">
				<text>订单编号：{{item.order_no}}</text>
				<text v-if="item.order_status==1">待支付</text>
				<text v-if="item.order_status==10">拣货中</text>
				<text v-if="item.order_status==15">待发货</text>
				<text v-if="item.order_status==20">已发货</text>
				<text v-if="item.order_status==30">已完成</text>
				<text v-if="item.order_status==40">售后</text>
				<text v-if="item.order_status==90">已取消</text>
			</view>
			<view class="mar-top-20 radius-16 display align-items" v-for="itemx in item.goods">
				<image :src="itemx.image_text" class="proudct-item-icon-10 radius-16" mode=""></image>
				<view class="ml20 right_width">
					<view class="text-clamp-1 fontSize-28">{{itemx.name}}</view>
					<view class="display-sb align-items mar-top-20 fontSize-26">
						<text>{{itemx.sku_name}}</text><text>x{{itemx.num}}</text>
					</view>
					<view class="mar-top-22 fontSize-28 col-E23737"><text class="fontSize-20">￥</text>{{itemx.price}}</view>
				</view>
			</view>
			<view class="mar-top-30" v-if="order_type==1">
				<view class="fontSize-26 display align-items" v-if="item?.order_status==1">请在<tm-countdown ref="cu" color="#E23737" :autoStart="true" :time="item.count_down" @end="endtime(item.id)"  format="MM分SS秒"></tm-countdown>内付款</view>
				<view class="display-sb align-items">
					<view class="fontSize-26">{{item.create_time}}</view>
					<view class="display align-items">
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 borderccc" v-if="item.order_status==15" @click.stop="_applyAfter(item.id,1)">申请退款</view>
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 borderccc" v-if="item.order_status==20" @click.stop="goviewLogistics(item.id)">查看物流</view>
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 borderccc col-9" v-if="item.order_status==1" @click.stop="_cancel_order(item.id)">取消订单</view>
						<view class="pad-lr-24 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20" v-if="item.order_status==1" @click.stop="wxpay(item.id)">去付款</view>
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 borderccc ml20"  v-if="item.is_refund==1&&item.order_status!=15" @click.stop="_applyAfter(item.id,3)">申请售后</view>
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20" v-if="item.order_status==20" @click.stop="_confirm_order(item.id)">确认收货</view>
						<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20" v-if="item.order_status==30&&item.evaluate_status==0">评价</view>
					</view>
				</view>
			</view>
			<view class="mar-top-30" v-if="order_type==2">
				<view class="display-sb align-items">
					<view class="fontSize-26">{{item.create_time}}</view>
					<view class="display align-items">
						<view class="pad-lr-12 pad-tb-12 fontSize-26 radius-30 borderccc" v-if="item.order_status==20" @click.stop="goviewLogistics(item.id)">查看物流</view>
						<view class="pad-lr-24 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20" v-if="item.order_status==15">发货</view>
					</view>
				</view>
			</view>
		</view>
		<view class="display-ce align-items" v-if="List.length==0">
			<tm-result :showBtn="false" subTitle=" " title="暂无数据" color="#bc8c1e"></tm-result>
		</view>
	</view>
	</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import {orderList,payOrder,cancelOrder,confirmReceipt,shoporderList} from '@/utils/api'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app';

// 声明微信支付相关类型
declare const WeixinJSBridge: any;
declare const wx: any;
onLoad((options)=>{
	console.log('订单列表页面加载，参数：', options);
	current.value = options.state
	order_type.value = options.type || 1  // 如果没有传递type参数，默认为1（会员订单）
	console.log('设置后的值 - current:', current.value, 'order_type:', order_type.value);
})
onShow(()=>{
	console.log('订单列表页面显示，order_type:', order_type.value);
	page.value = 1
	List.value = []
	if(order_type.value==1){
		console.log('调用会员订单API');
		_order_list()
	}else{
		console.log('调用商家订单API');
		_shoporderList()
	}
})
onReachBottom(()=>{
	if(page.value>1){
		if(order_type.value==1){
			_order_list()
		}else{
			_shoporderList()
		}
	}
})
const nav_list = ref([
	{id:1,name:'全部',state:0},
	{id:2,name:'待支付',state:1},
	{id:4,name:'待发货',state:2},
	{id:5,name:'待收货',state:3},
	{id:6,name:'已完成',state:4},
])
const current = ref(nav_list.value[0].state),
	  order_type=ref(1)//1-会员订单，2-商家订单
//订单列表数据-----用户
const List = ref([])
const page = ref(1)
const _order_list =() =>{
	console.log('获取订单列表，参数：', {status:current.value,page:page.value,limit:10});
	orderList({status:current.value,page:page.value,limit:10}).then(res=>{
		console.log('订单列表API返回：', res);
		if(res.code==1){
			console.log('订单数据：', res.data);
			if(res.data && res.data.order && res.data.order.data) {
				List.value = List.value.concat(res.data.order.data)
				if(res.data.order.data.length>0){
					page.value++
				}
			} else {
				console.log('订单数据结构异常：', res.data);
			}
		} else {
			console.log('API返回错误：', res.msg);
		}
	}).catch(err => {
		console.error('获取订单列表失败：', err);
	})
}
//订单列表数据--------商家
const _shoporderList=()=>{
	console.log('获取商家订单列表，参数：', {status:current.value,page:page.value,limit:10});
	shoporderList({status:current.value,page:page.value,limit:10}).then(res=>{
		console.log('商家订单列表API返回：', res);
		if(res.code==1){
			console.log('商家订单数据：', res.data);
			if(res.data && res.data.order && res.data.order.data) {
				List.value = List.value.concat(res.data.order.data)
				if(res.data.order.data.length>0){
					page.value++
				}
			} else {
				console.log('商家订单数据结构异常：', res.data);
			}
		} else {
			console.log('商家订单API返回错误：', res.msg);
		}
	}).catch(err => {
		console.error('获取商家订单列表失败：', err);
	})
}
const change = (id:number) =>{
	current.value = id
	page.value=1
	List.value = []
	if(order_type.value==1){
		_order_list()
	}else{
		_shoporderList()
	}
}
//倒计时结束
const endtime =(id:number) =>{
	cancelOrder({id:id}).then(res=>{
		if(res.code==1){
			List.value.forEach((item,index)=>{
					item.order_status = 90
			})
		}
	})
}
//取消订单
const _cancel_order =(id:number|string) =>{
	uni.showModal({
			title:'提示',
			content:'是否取消订单？',
			success: function (res) {
					if (res.confirm) {
						cancelOrder({id:id}).then(res=>{
							uni.showToast({
									icon: 'none',
									title:res.msg
								})
							if(res.code==1){
								List.value.forEach((item,index)=>{
									if(item.id==id){
										item.order_status = 90
									}
								})
							}
						})
					} else if (res.cancel) {
					}
				}
		})
}
//确认收货
const _confirm_order =(id:number) =>{
	uni.showModal({
			title:'提示',
			content:'是否确认收货？',
			success: function (res) {
					if (res.confirm) {
						confirmReceipt({id:id}).then(res=>{
							uni.showToast({
									icon: 'none',
									title:res.msg
								})
							if(res.code==1){
								List.value.forEach((item,index)=>{
									if(item.id==id){
										item.order_status = 30
									}
								})
							}
						})
					} else if (res.cancel) {
					}
				}
		})
}
const wxpay =(id:string) =>{
	payOrder({
		id:id,
	}).then(res=>{
		if(res.code==1){
			// 特殊处理：当data为null且msg包含"待对接微信支付"时，直接跳转支付成功
			if (!res.data && res.msg && res.msg.includes('待对接微信支付')) {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				});
				// 更新订单状态
				List.value.forEach(item=>{
					if(item.id==id){
						item.order_status = 15
					}
				})
				setTimeout(() => {
					uni.redirectTo({
						url:'/indexpages/paysuccess/paysuccess?type=2&order_id=' + id
					})
				}, 2000);
				return;
			}
			
			let data = JSON.parse(JSON.stringify(res.data))
			// 调用微信支付
			callWechatPayInOrderList(data, id)
		}else{
			uni.showToast({
				icon: 'none',
				title:res.msg
			})
		}
	})
}
const gomap = (info) =>{
	uni.openLocation({
		latitude:Number(info.merchant_lat),
		longitude:Number(info.merchant_lng),
		address:info.merchant_full_address,
		name:info.merchant_name
	})
}
const goorderdetails =(id:string|number) =>{
	uni.navigateTo({
		url:'/mypages/orderdetails/orderdetails?order_id='+id+'&order_type='+order_type.value
	})
}
const goservice =() =>{
	uni.navigateTo({
		url:'/mypages/service/service'
	})
}
const goseecode =(id:number)=>{
	uni.navigateTo({
		url:'/indexpages/seecode/seecode?order_id='+id
	})
}
//申请退款
const _applyAfter = (id,type) =>{
	uni.navigateTo({
		url:'/mypages/service/service?return_type='+type+'&order_id='+id
	})
}
const goshopgoods = (id) =>{
	uni.navigateTo({
		url:'/indexpages/shopgoods/shopgoods?id='+id
	})
}
// 调用微信支付
const callWechatPayInOrderList = (payData: any, orderId: string) => {
	console.log('开始调用微信支付:', payData);
	console.log('WeixinJSBridge 存在:', typeof WeixinJSBridge !== 'undefined');
	console.log('wx 存在:', typeof wx !== 'undefined');
	
	// 等待微信环境加载完成
	const tryWechatPay = () => {
		if (typeof WeixinJSBridge !== 'undefined') {
			console.log('使用 WeixinJSBridge 调用微信支付');
			// 使用WeixinJSBridge调用微信支付
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				appId: payData.appId,
				timeStamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign
			}, (result: any) => {
				console.log('WeixinJSBridge 支付结果:', result);
				handlePayResultInOrderList(result, orderId);
			});
		} else if (typeof wx !== 'undefined') {
			console.log('使用 wx.chooseWXPay 调用微信支付');
			// 使用微信JS-SDK的支付接口
			wx.chooseWXPay({
				timestamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign,
				success: (result: any) => {
					console.log('wx.chooseWXPay 支付成功:', result);
					handlePayResultInOrderList({err_msg: 'get_brand_wcpay_request:ok'}, orderId);
				},
				cancel: (result: any) => {
					console.log('wx.chooseWXPay 支付取消:', result);
					handlePayResultInOrderList({err_msg: 'get_brand_wcpay_request:cancel'}, orderId);
				},
				fail: (result: any) => {
					console.log('wx.chooseWXPay 支付失败:', result);
					handlePayResultInOrderList({err_msg: 'get_brand_wcpay_request:fail'}, orderId);
				}
			});
		} else {
			console.log('微信支付环境检查失败，等待加载...');
			// 如果微信环境还没加载完成，等待一下再试
			setTimeout(() => {
				if (typeof WeixinJSBridge !== 'undefined' || typeof wx !== 'undefined') {
					tryWechatPay();
				} else {
					uni.showToast({
						title: '请在微信中打开',
						icon: 'none'
					});
				}
			}, 1000);
		}
	};
	
	tryWechatPay();
}

// 处理支付结果
const handlePayResultInOrderList = (result: any, orderId: string) => {
	if (result.err_msg === 'get_brand_wcpay_request:ok') {
		uni.showToast({
			icon: 'none',
			title: '支付成功！'
		})
		List.value.forEach(item=>{
			if(item.id==orderId){
				item.order_status = 15
			}
		})
	} else if (result.err_msg === 'get_brand_wcpay_request:cancel') {
		uni.showToast({
			icon: 'none',
			title: '已取消支付！'
		})
	} else {
		uni.showToast({
			icon: 'none',
			title: '支付失败！'
		})
	}
}

const goviewLogistics = (id) =>{
	uni.navigateTo({
		url:'/mypages/viewLogistics/viewLogistics?id='+id
	})
}
</script>

<style lang="scss">
@import 'orderlist.scss';
</style>
